package com.atguigu.gulimall.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * @author bairimengchang
 * @version 1.0
 * @project gulimall
 * @description 网关的跨域允许配置，用来回复预检请求（请求方式 OPTIONS），告诉他后台允许跨域访问
 * @date 2024/11/24
 */
@Configuration
public class GulimallCorsConfiguration {

    /*
     * 跨域配置，配置完后可以通过查看预检请求（请求方式 OPTIONS）的响应标头信息。
     * 没有配置之前是没有响应标头信息的
     * HTTP/1.1 200 OK
     * Vary: Origin
     * Vary: Access-Control-Request-Method
     * Vary: Access-Control-Request-Headers
     * Access-Control-Allow-Origin: http://localhost:8001
     * Access-Control-Allow-Methods: POST
     * Access-Control-Allow-Headers: content-type, token
     * Access-Control-Allow-Credentials: true
     * content-length: 0
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        // 配置跨域信息配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 配置跨域
        // 允许所有头
        corsConfiguration.addAllowedHeader("*");
        // 允许所有请求方法
        corsConfiguration.addAllowedMethod("*");
        // 允许所有请求来源
        corsConfiguration.addAllowedOrigin("*");
        // 允许携带cookie
        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**", corsConfiguration);
        // 返回的是SpringBoot的跨域过滤器，用于处理响应给前端的信息
        return new CorsWebFilter(source);
    }

}
